package net.sunzc.yunlian.controller;

import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.Log;
import javafx.application.Platform;
import net.sunzc.yunlian.utils.Utils;
import net.sunzc.yunlian.view.ScreenWindow;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 控制器类，负责界面与底层交互的 中间层。
 * 也是各种功能的逻辑实现
 * Created by Administrator on 2016/7/13.
 */
public class DeviceController extends Thread implements AndroidDebugBridge.IDeviceChangeListener, AndroidDebugBridge.IDebugBridgeChangeListener {
    private static final String TAG = "DeviceController";
    private static DeviceController controller = new DeviceController();
    private static LinkedHashMap<String, ScreenWindow> connectedDevices = new LinkedHashMap<>();
    private static List<String> DEVICES = new ArrayList<String>() {
        private static final long serialVersionUID = 5519099250622552835L;

        {
            for (int index = 3; index <= 13; index++) {
                add("zte" + index);
            }
        }
    };
    private ScreenListener screenListener;

    private DeviceController() {
    }

    public static DeviceController startADB() {
        if (!controller.isAlive())
            controller.start();
        return controller;
    }

    public void setScreenListener(ScreenListener screenListener) {
        this.screenListener = screenListener;
    }

    @Override
    public void deviceConnected(IDevice device) {
        if (device.isEmulator()) return;
//        if (DEVICES.contains(device.getSerialNumber()))
        Utils.threadPool.execute(new ScreenStarter(device, screenListener));
    }

    @Override
    public void deviceDisconnected(IDevice device) {
        Log.i(TAG, "有设备断开:" + device.toString());
        ScreenWindow screenWindow = connectedDevices.remove(device.getSerialNumber());
        if (screenWindow == null) return;
        Platform.runLater(() -> {
            if (screenListener != null)
                screenListener.removeScreen(screenWindow);
        });
    }

    @Override
    public void deviceChanged(IDevice device, int changeMask) {
        Log.i(TAG, "adb是否连接:" + device.isOnline() + "changeMask:" + changeMask);
    }

    @Override
    public void run() {
        AndroidDebugBridge.init(false);
        File adbFile = new File(System.getProperty("user.dir"), "adb.exe");
        if (!adbFile.exists()) {
            Log.i(TAG, "adb没有找到");
        }
        AndroidDebugBridge.createBridge(adbFile.getAbsolutePath(), true);
        AndroidDebugBridge.addDebugBridgeChangeListener(this);
        AndroidDebugBridge.addDeviceChangeListener(this);
    }

    @Override
    public void bridgeChanged(AndroidDebugBridge bridge) {
        Log.i(TAG, "adb是否连接:" + bridge.isConnected());
    }

    public interface ScreenListener {
        void addScreen(ScreenWindow screen);

        void removeScreen(ScreenWindow screen);
    }

    private static class ScreenStarter implements Runnable {
        private ScreenListener screenListener;
        private IDevice device;

        ScreenStarter(IDevice device, ScreenListener screenListener) {
            this.device = device;
            this.screenListener = screenListener;
        }

        @Override
        public void run() {
            int counter = 0;
            int COUNTER_LIMIT = 5;
            while (device.isOffline() && counter < COUNTER_LIMIT) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                counter++;
            }
            if (counter >= COUNTER_LIMIT) {
                Log.e(TAG, "连接失败" + device.getSerialNumber());
                return;
            }
            ScreenWindow screenWindow = new ScreenWindow(device);
            connectedDevices.put(device.getSerialNumber(), screenWindow);
            if (screenListener != null) {
                Platform.runLater(() -> {
                    screenListener.addScreen(screenWindow);
                });
            }
        }
    }
}
